import json

from django.contrib.auth import logout
from django.core.cache import cache
from django.http import JsonResponse

# Create your views here.
from django.views import View

from apps.areas.models import Area

from apps.areas.models import Address
from utils.views import LoginRequiredJSONMixin


class AreasView(View):
    def get(self,request):

        province_list=cache.get('provinces')
        print(province_list)
        if not province_list:
            print('省市区没有缓存')

            # 1.去数据库查询所有的省份数据
            try:
                areas=Area.objects.filter(parent=None)
            except Exception as e:
                print(e)
                return JsonResponse({'code':400,'errmsg':"获取省份失败,网络异常"})

            province_list=[]
            for a in areas:
                # print(a)
                province_list.append({"id":a.id,"name":a.name})
            # 如果缓存是空,去musql查 查完后再存入缓存
            cache.set('provinces',province_list,3600*24*30)
        else:
            print('使用了缓存')

        # 返回
        return JsonResponse({'code':0, 'province_list': province_list})


class SubAreasView(View):
    def get(self,request,area_id):
        # 去缓存找
        subs=cache.get('cities_%s' % area_id)
        if not subs:
            print('没有市区的缓存')
            # 根据上一级的id获取下一级的数据(数据库操作)
            try:
                subareas=Area.objects.filter(parent_id=area_id)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': "获取市区失败,网络异常"})

            # 把下一级数据做拼接
            subs=[]
            for a in subareas:
                subs.append({'id':a.id,'name':a.name})

            # 把数据存到缓存里
            cache.set('cities_%s' % area_id,subs,3600*24*30)



        return JsonResponse({'code':0,'sub_data':{'subs':subs}})


# 新增收货地址
class AddressView(LoginRequiredJSONMixin,View):

    def post(self,request):
        print('走了码？')
        # 1.获取传来的参数
        body=request.body
        data_dict=json.loads(body)
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')

        # 2.校验
        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return  JsonResponse({'code':400,'errmsg':'数据不全'})
        # 使用Address模型类 添加数据
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            # 设置address为默认地址
            print('address',address)
            request.user.default_address=address.id

            request.user.save()

        except Exception as e:
            print(e)
            return JsonResponse({'code': 505, 'errmsg': '保存失败'})


        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }


        # 返回成功信息
        return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})

    def get(self,request):

        # 获取用户对象
        user=request.user
        # 获取所有地址
        # addresses=Address.objects.all(user=user)
        try:
            # addresses=user.addresses.all()
            addresses = Address.objects.filter(user=request.user,
                                               is_deleted=False)
            # 创建一个空列表存地址的字典数据
            address_dict_list=[]
            # 循环拼接字典 添加到列表里
            for address in addresses:
                address_dict = {
                     "id": address.id,
                     "title": address.title,
                     "receiver": address.receiver,
                     "province": address.province.name,
                     "city": address.city.name,
                     "district": address.district.name,
                     "place": address.place,
                     "mobile": address.mobile,
                     "tel": address.tel,
                     "email": address.email
                }
                # 拼接列表(将默认地址移动到最前面)
                default_address=request.user.default_address
                print(default_address)
                if default_address==address.id:
                    address_dict_list.insert(0, address_dict)
                else:
                    address_dict_list.append(address_dict)


        except Exception as e:
            print(e)
            return JsonResponse({'code':501,'errmsg':'查询失败'})

        # 返回
        return  JsonResponse({'code':0,'errmsg':'ok','addresses':address_dict_list,'default_address_id':request.user.default_address})


# 修改删除
class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    def put(self,request,address_id):
        # 接收参数
        body = request.body
        data_dict = json.loads(body)
        receiver=data_dict.get('receiver')
        province_id=data_dict.get('province_id')
        city_id=data_dict.get('city_id')
        district_id=data_dict.get('district_id')
        place=data_dict.get('place')
        mobile=data_dict.get('mobile')
        tel=data_dict.get('tel')
        email=data_dict.get('email')

        # 校验参数
        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return  JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        # 其他校验暂时省略

        # 判断地址是否存在,并更新地址信息地址
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'errmsg':'更新地址失败'})


        # 构造响应数据
        address = Address.objects.get(id=address_id)

        address_dict = {
            "id":address.id,
            "title":address.title,
            "receiver":address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址信息
        return JsonResponse({'code':0,'errmsg':'更新地址成功','address':address_dict})

    def delete(self,request,address_id):
        try:
            # 查看要删除的地址
            address=Address.objects.get(id=address_id)
            # 将地址逻辑删除设置为True
            address.is_deleted=True
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'errmsg':'删除地址失败'})

        # 响应删除地址结果
        return JsonResponse({'code':0,'errmsg':'删除地址成功'})


# 设置默认地址
class DefaultAddressView(LoginRequiredJSONMixin,View):
    def put(self,request,address_id):
        try:
            # 接收参数
            address=Address.objects.get(id=address_id)
            print('aaa',address)
            # 设置地址为默认地址
            request.user.default_address=address.id
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'errmsg':'设置默认地址失败'})
        # 响应设置默认地址结果
        return JsonResponse({'code':0,'errmsg':'设置默认地址成功'})


# 修改地址标题
class UpdateTitleAddressView(LoginRequiredJSONMixin,View):
    def put(self,request,address_id):
        json_dict=json.loads(request.body.decode())
        title=json_dict.get('title')
        try:
            # 查询地址
            address=Address.objects.get(id=address_id)
            # 设置新的地址标题
            address.title=title
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'errmsg':'设置地址标题失败'})

        # 返回
        return JsonResponse({'code':0,'errmsg':'设置地址标题成功'})


# 修改密码
class ChangePasswordView(View):
    def put(self,request):
        # 接收参数
        dict=json.loads(request.body.decode())
        old_password=dict.get('old_password')
        new_password=dict.get('new_password')
        new_password2=dict.get('new_password2')

        # 校验参数
        if not all([old_password,new_password,new_password2]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        result=request.user.check_password(old_password)
        if not result:
            return  JsonResponse({'code':400,'errmsg':'原始密码不正确'})

        if new_password !=new_password2:
            return JsonResponse({'code':400,'errmsg':'两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'errmsg':'修改密码失败'})
        # 清理状态保持信息
        logout(request)
        response=JsonResponse({'code':0,'errmsg':'ok'})
        response.delete_cookie('username')
        return  response
